<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>报名系统</title>
  <style>
    td {
      cursor: pointer;
    }
  </style>
</head>

<body>
  <h1>学生管理系统</h1>
  <p>学生姓名：<input type="text" class="user"></p>
  <p>学生年龄：<input type="text" class="age"></p>
  <button class="add-stu">添加学生</button>
  <table class="stu-info" border="" cellspacing="0" style="text-align: center">
    <tr>
      <th>学生姓名</th>
      <th>年龄</th>
      <th>操作</th>
      
    </tr>
  </table>
  <script>
    let stuInfo = document.querySelector(".stu-info");
    let addStu = document.querySelector(".add-stu");
    let user = document.querySelector(".user");
    let age = document.querySelector(".age");
    // 建立数组
    let stus =
      [
        { "name": "zhangsan", "age": 18 },
        { "name": "lisi", "age": 19 },
        { "name": "wangwu", "age": 20 }
      ]
      // 拼接
    for (let i = 0; i < stus.length; i++) {
      let tr = document.createElement("tr");
      tr.innerHTML = `
      <td class = username>${stus[i].name}</td>
         <td>${stus[i].age}</td>
         <td>删除</td>
      `
      // 插入tr
      stuInfo.appendChild(tr)
      let del = tr.children[tr.children.length - 1]; // 找到最后一个删除
      del.addEventListener("click", function () {
        this.parentNode.remove(); // 删除他的父级,就将表格的一行都删除了
      })
    }

    // 注册点击事件
    addStu.addEventListener("click", function () {
      let username = document.querySelectorAll(".username")
      for (let i = 0; i < username.length; i++) {
        if (username[i].textContent == user.value) {
          alert("添加失败");
          return;
        }
      }
      let tr = document.createElement("tr");
      tr.innerHTML = `
            <td class = username>${user.value}</td>
            <td>${age.value}</td>
            <td class="btn">删除</td>
            `
      stuInfo.appendChild(tr)
      let del = tr.children[tr.children.length - 1];
      del.addEventListener("click", function () {
        this.parentNode.remove();
      })
    })



  </script>
</body>
<!--  let tr = document.createElement("tr");
tr.innerHTML = `
<td>${user.value}</td>
<td>${age.value}</td>
<td class="btn">删除</td>
`
stuInfo.appendChild(tr)
let del = tr.children[tr.children.length - 1]; // 找到最后一个删除
del.addEventListener("click", function () {
this.parentNode.remove(); // 删除他的父级,就将表格的一行都删除了
}) -->

</html>